/**
    Copyright (c) 2010 ATTi 
    All rights reserved.
    Author: Michael Shu
    Date: 9/29/2010
*/

trigger QuoteAASFieldUpdate on Quote (before insert, before update, after update, after insert) 
{
    if(trigger.isBefore){
        Set<ID> oppIds_proposal = new Set<ID>();
        Set<ID> oppIds_rfp  = new Set<ID>();
        Set<ID> oppIdsQtrequest = new Set<ID>();
        if(trigger.isInsert){
            for(Quote q : trigger.new)
            {
                if(q.Status == AASFieldUpdateHelperClass.Proposal_Submitted)
                {
                    oppIds_proposal.add(q.OpportunityId);
                }
                if(q.Status == AASFieldUpdateHelperClass.RFP_Submitted)
                {
                    oppIds_rfp.add(q.OpportunityID);
                }
            }
            AASFieldUpdateHelperClass.updateAASQuotefieldsInInsert(trigger.new);        
        }
        else if(trigger.isUpdate)
        {
            for(Quote q : trigger.new){
                Quote oldQ = trigger.oldMap.get(q.Id);
                if(oldQ.Status != q.Status)
                {
                    if(q.Status == AASFieldUpdateHelperClass.Proposal_Submitted){
                        oppIds_proposal.add(q.OpportunityId);
                    }
                    if(q.Status == AASFieldUpdateHelperClass.RFP_Submitted){
                        oppIds_rfp.add(q.OpportunityID);
                    }
                    if(q.Status=='Quote Requested')
                    {
                    oppIdsQtrequest.add(q.OpportunityID);
                    }
                }
            }
        }
        //Added by naidu
        if(oppIdsQtrequest.size()>0)
        {
            Map<Id,Opportunity> mapOpportunity=new Map<Id,Opportunity>([Select Proposal_Origin__c,LeadSource,Credit_Check_Info_Secured__c,Contract_Termination_Date__c,Contract_Start_Date__c From Opportunity where id in:oppIdsQtrequest]);
            for(Quote q : trigger.new)
            {
                if(q.Status=='Quote Requested')
                {
                    Opportunity opp=mapOpportunity.get(q.OpportunityID);
                    
                    /*
                       udpated by plo, 11/28/2011
                       
                       AD-25582 
                       (1) Separate out validation error rules when quote is moving to Quote Requested
                    */
                    
                    String errMsg = '';
                    /*if(opp.Proposal_Origin__c==null || opp.LeadSource==null || opp.Credit_Check_Info_Secured__c==null || opp.Contract_Termination_Date__c==null || opp.Contract_Start_Date__c==null)
                    {
                        q.addError('Proposal Origin,Lead Source,Credit Check Info Secured,Campaign Start Date,Campaign End Date is required with this status');
                    }*/
                    List<String> reqFieldAPINames = new List<String>{'Proposal_Origin__c', 'LeadSource', 'Credit_Check_Info_Secured__c', 'Contract_Termination_Date__c', 'Contract_Start_Date__c'};
                    Map<String,sObjectField> oppFieldMap = opp.getSObjectType().getDescribe().fields.getMap();
                    Integer errFieldCount = 0;
                    for(String s : reqFieldAPINames)
                    {
                       if(opp.get(s) == null && oppFieldMap.containskey(s))
                       {
                          String fieldLabel = oppFieldMap.get(s).getDescribe().getLabel();
                          errMsg += ' ' + fieldLabel + ',';
                          errFieldCount++;
                       }
                    }
                    
                    if(errFieldCount > 0)
                    {
                    	   String verb = 'is';
                    	   errMsg = errMsg.substring(0,errMsg.length()-1); // take out the extra space + comma

                    	   if(errFieldCount > 1)
                    	      verb = 'are';
                    	                       	   
                    	   errMsg += ' ' + verb + ' required with this status.';
                        q.addError(errMsg);
                    }
                }
            }
        }
        
        if(!oppIds_proposal.isEmpty() || !oppIds_rfp.isEmpty()){
            AASFieldUpdateHelperClass.updateAASOppsFromQuote(oppIds_proposal, oppIds_rfp);
        }
    }
	else // after trigger, update for AD-24156 & AD-24230
	{
		Set<Id> quoteIds = new Set<Id>();
		
		/* needs to let the user defined validation rules run first, and there are no Quote updates */
		if(trigger.isInsert || trigger.isUpdate)
		{
		   // to avoid duplicated Task creatsions by workflow update firing Quote Update trigger again
		   if(!AASFieldUpdateHelperClass.IsAASQuoteTaskCreated)
		   {
			   for(Quote q : trigger.new)
			   {
			      /* AD-24230 */
			      if(q.Status == AASFieldUpdateHelperClass.Proposal_Submitted || q.Status == AASFieldUpdateHelperClass.RFP_Submitted)
			      {
			         Boolean isInclude = false;	
			      	
			         if(trigger.isInsert)
			         {
			         	/* only include Quotes that has Status "Quote Requested" or "Quote Returned" on creation */
			         	isInclude = true;
			         }
			         else if(trigger.isUpdate)
			         {
			         	/* only include Quotes that has Status changed */
			         	Quote oldQ = trigger.oldMap.get(q.Id);
			         	if(oldQ.Status != q.Status)
			         	{
			               isInclude = true;
			         	}
			         }
			         
			         if(isInclude)
			            quoteIds.add(q.Id);
			      }
			   }
			   
			   /* AD-24230, B1 b), B2 b) */
			   if(!quoteIds.isEmpty())
			   {
			      AASFieldUpdateHelperClass.createAASQuoteTasksByStatus(quoteIds);
			   }
		   }
		}
	}
}